import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import Textarea from '@/components/Textarea'
import { RootState } from '@/store'
import { clearAuth, editUserPhoto, editUserProfile, getUserProfile } from '@/store/action/user'
import { Profile } from '@/store/reducers/user'
import { Dialog, List, Popup, Toast } from 'antd-mobile'
import { DatePicker } from 'antd-mobile/es/components/date-picker/date-picker'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import dayjs from 'dayjs'
import history from '@/utils/history'
import { removeTokenInfo } from '@/utils/storage'

type PopupBottom = {
  visible: boolean
  type: 'photo' | 'gender' | ''
}

type PopupRight = {
  visible: boolean
  type: 'name' | 'intro' | ''
}

export default function ProfileEdit() {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])
  const { profile } = useSelector((state: RootState) => state.user)

  const [popupBottom, setPopupBottom] = useState<PopupBottom>({ visible: false, type: '' })
  const [popupRight, setPopupRight] = useState<PopupRight>({ visible: false, type: '' })
  const [name, setName] = useState('')

  const [intro, setIntro] = useState('')

  const [pickerShow, setPickerShow] = useState(false)

  const fileRef = useRef<HTMLInputElement>(null)

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      console.log('file', e.target.files[0])
      const file = e.target.files[0]
      const fd = new FormData()
      fd.append('photo', file)
      dispatch(editUserPhoto(fd))
      setPopupBottom({ visible: false, type: '' })
    }
  }

  const closePopup = () => {
    setPopupBottom({ visible: false, type: '' })
    setPopupRight({ visible: false, type: '' })
  }

  //编辑其他资料
  const handleUpdateProfile = async (data: Partial<Profile>) => {
    await dispatch(editUserProfile(data))
    Toast.show({ content: '更新成功' })
    closePopup()
  }

  //打开右侧弹出层的时候设置值
  const pupupRightOpen = (type: 'name' | 'intro') => {
    if (type === 'name') {
      setName(profile.name)
    } else if (type === 'intro') {
      if (profile.intro) setIntro(profile.intro)
    }
    setPopupRight({ visible: true, type: type })
  }

  //提交编辑
  const SubmitProfile = () => {
    if (popupRight.type === 'name') {
      handleUpdateProfile({ name })
    } else if (popupRight.type === 'intro') {
      handleUpdateProfile({ intro })
    }
  }

  //提交编辑（键盘回车）
  const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      SubmitProfile()
    }
  }

  //生日确定事件
  const handleConfirm = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')
    handleUpdateProfile({ birthday })
  }

  //退出业务
  const handleLogout = () => {
    Dialog.confirm({
      cancelText: '我再想想',
      confirmText: '狠心退出',
      title: '温馨提示',
      content: '是否退出登录',
      onConfirm: () => {
        console.log('用户点击了确认，我们需要实现退出登录功能')
        // console.log('用户点击了确认，我们需要实现退出登录功能')
        // 清除本地存储的 token
        removeTokenInfo()
        // 清除 redux 中的 token
        dispatch(clearAuth())
        // 跳转到登录页
        history.push('/login')
        // 提示
        Toast.show({ content: '退出成功' })
      },
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => setPopupBottom({ visible: true, type: 'photo' })}
            >
              头像
            </List.Item>

            <List.Item arrow extra={profile.name} onClick={() => pupupRightOpen('name')}>
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => pupupRightOpen('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => setPopupBottom({ visible: true, type: 'gender' })}
            >
              性别
            </List.Item>
            {/* 先利用ant mobile中的DatePicker组件， 运用dayjs这个第三方库来格式化时间 */}
            <List.Item arrow extra={profile.birthday} onClick={() => setPickerShow(true)}>
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            ref={fileRef}
            className="avatar-upload"
            type="file"
            accept=".png,.jpg"
            onChange={(e) => handleFileChange(e)}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogout}>
            退出登录
          </button>
        </div>

        {/* 底部弹出层 */}
        <Popup
          visible={popupBottom.visible}
          position="bottom"
          bodyClassName="popup-bottom-list"
          onMaskClick={closePopup}
        >
          {popupBottom.type === 'photo' ? (
            <>
              <div className="list-item" onClick={() => fileRef.current?.click()}>
                拍照
              </div>
              <div className="list-item" onClick={() => fileRef.current?.click()}>
                本地选择
              </div>{' '}
            </>
          ) : (
            <>
              <div className="list-item" onClick={() => handleUpdateProfile({ gender: 0 })}>
                男
              </div>
              <div className="list-item" onClick={() => handleUpdateProfile({ gender: 1 })}>
                女
              </div>
            </>
          )}

          <div className="list-item" onClick={closePopup}>
            取消
          </div>
        </Popup>
        {/* 右侧弹出层 */}
        {/* 不可见时卸载内容 destroyOnClose 否则自动获取焦点只有第一次生效*/}
        <Popup destroyOnClose visible={popupRight.visible} position="right" bodyClassName="popup-right">
          <NavBar onBack={() => closePopup()} right={<span onClick={() => SubmitProfile()}>提交</span>}>
            编辑用户信息
          </NavBar>
          {popupRight.type === 'name' ? (
            <>
              <div className="edit-content">
                <h3 className="edit-title">编辑昵称</h3>
                <Input
                  className="edit-input"
                  value={name}
                  autoFocus
                  onChange={(e) => setName(e.target.value)}
                  onKeyUp={(e) => handleKeyUp(e)}
                />
              </div>
            </>
          ) : (
            <>
              <div className="edit-content">
                <h3 className="edit-title">编辑简介</h3>
                {/* 如何解决自动光标在首格呢 input.setSelectionRange(-1,-1) 要在封装的组件中用ref得到原生的标签 */}
                <Textarea autoFocus value={intro} onChange={(e) => setIntro(e.target.value)} placeholder="请输入简介" />
              </div>
            </>
          )}
        </Popup>

        {/* 日期选择器 */}
        <DatePicker
          visible={pickerShow}
          min={new Date('1940-01-01')}
          max={new Date()}
          value={new Date(profile.birthday)}
          onClose={() => setPickerShow(false)}
          onConfirm={(e: Date) => handleConfirm(e)}
        />
      </div>
    </div>
  )
}
